//
//  HMUserAccountViewModel.swift
//  WeiBoXR
//
//  Created by acer on 16/9/23.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit

class HMUserAccountViewModel: NSObject {

    static let sharedUserAccountViewModel: HMUserAccountViewModel = HMUserAccountViewModel()
    var userAccountModel: HMUserAccountModel? {
        return HMUserAccountModel.loadUserAccountModel()
    }
    
    var accessToken: String? {
        
        let token = userAccountModel?.access_token
        let expiresDate = userAccountModel?.expiresDate
        
        if let t = token {
            if expiresDate?.compare(Date()) == .orderedDescending {
                return t
            }else {
                return nil
            }
        } else {
            return nil
        }
    }
    
    
    var isLogin : Bool {
        return accessToken != nil
    }
    //  通过Accesstoken获取用户信息
    func requestAccesstoken(code: String ,callBack: @escaping (Bool)->())  {
        
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("\(error)")
                callBack(false)
                return
            }
            guard let dic = response as? [String : Any] else {
                print("字典格式不正确")
                callBack(false)
                return
            }
            let userAccountModel = HMUserAccountModel(dic : dic)
            //            print(userAccountModel.access_token)
            self.requestUserInfo(userAccountModel: userAccountModel, callBack: callBack)
        }
    }
    func requestUserInfo(userAccountModel: HMUserAccountModel, callBack: @escaping (Bool)->())  {
        
        HMNetworkTools.sharedTools.requestUserInfo(accessToken: userAccountModel.access_token!, uid: userAccountModel.uid) { (response, error) in
            if error != nil {
                print("\(error)")
                callBack(false)
                return
            }
            guard let dic = response as? [String : Any] else {
                print("字典格式不正确")
                callBack(false)
                return
            }
            let name = dic["name"]
            //user头像 large:avatar_large , 高清：avatar_hd
            let avatar_large = dic["avatar_large"]
            //            let profile_image_url = dic["profile_image_url"]
            
            userAccountModel.name = name as? String
            //            userAccountModel.profile_image_url = profile_image_url as? String
            userAccountModel.avatar_large = avatar_large as? String
            
            userAccountModel.saveUserAccount()
            
            callBack(true)
        }
    }
}
